<template>
  <div class="login">
    <el-container class="bg">
      <el-container>
        <el-main>
          <div class="box">
            <div style="text-align:center;margin-bottom:24px;">
              <h1 style="color:white">Xmall 商城</h1>
            </div>
            <el-card class="box-card">
              <el-tabs v-model="activeName">
                <el-tab-pane label="账号登录" name="password"></el-tab-pane>
                <el-tab-pane label="邮箱登录" name="email"></el-tab-pane>
              </el-tabs>
              <div v-if="activeName == 'password'">
                <el-form
                  label-position="left"
                  :model="form"
                  :rules="rules"
                  ref="form"
                  label-width="80px"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-row>
                      <el-col :span="20">
                        <el-input v-model="form.username" autofocus></el-input>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <el-row>
                      <el-col :span="20">
                        <el-input v-model="form.password"></el-input>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-row>
                      <el-col :span="20">
                        <el-button
                          class="validate"
                          id="TencentCaptcha"
                          data-appid="2086075100"
                          data-cbfn="callback"
                        >
                          点击按钮进行验证
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-row>
                      <el-col :span="5">
                        <el-checkbox-group
                          v-model="form.remember"
                          style="float:left"
                        >
                          <el-checkbox
                            label="记住我"
                            name="remember"
                          ></el-checkbox>
                        </el-checkbox-group>
                      </el-col>
                      <el-col :span="5">
                        <a
                          style="margin-left:14px"
                          href="#"
                          @click.prevent="activeName = 'email'"
                        >
                          忘记密码？
                        </a>
                      </el-col>
                      <el-col :span="5">
                        <el-button type="small" @click="jumpTo()">
                          去注册
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-row>
                      <el-col :span="20">
                        <el-button type="primary" @click="login()">
                          登录
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-form>
              </div>
              <div v-if="activeName == 'email'" class="form-data">
                <el-form label-position="left" ref="form" label-width="80px">
                  <el-form-item label="邮箱号码">
                    <el-row>
                      <el-col :span="14">
                        <el-input v-model="form.email" autofocus></el-input>
                      </el-col>
                      <el-col :span="6">
                        <el-button
                          class="validate"
                          style="float:left; "
                          @click="
                            getCode();
                            timer();
                          "
                        >
                          {{ text }}
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="验证码">
                    <el-row>
                      <el-col :span="20">
                        <el-input v-model="form.code"></el-input>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-row>
                      <el-col :span="20">
                        <el-button type="primary" @click="login('form')">
                          登录
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
        </el-main>
      </el-container>
      <el-footer>
        <span style="color:white">
          东莞理工学院17级实训 @第六组 &nbsp;&nbsp; &nbsp;&nbsp; _版权所有
        </span>
        <!-- <div style="dispaly: inline-block; float: left;">
          东莞理工学院17级实训 @第六组
          &nbsp;&nbsp; &nbsp;&nbsp; _版权所有
        </div> -->
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      activeName: "password",
      form: {
        username: "",
        password: "",
        email: "",
        remember: false
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      },
      // 验证是否通过
      btnClick: false,
      // error: false,
      validate: false,
      text: "发送验证码",
      times: 59,
      clock: null
    };
  },
  created() {
    
    // window.TencentCaptcha = undefined;
    // this.getAppId()
    let that = this;
    if (window.TencentCaptcha === undefined) {
      let script = document.createElement("script");
      let head = document.getElementsByTagName("head")[0];
      script.type = "text/javascript";
      script.chaset = "UTF-8";
      script.src = "https://ssl.captcha.qq.com/TCaptcha.js";
      head.appendChild(script);
    }
    else{
      window.location.reload();
    }
    window.callback = function(res) {
      // res（用户主动关闭验证码）= {ret: 2, ticket: null}
      // res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
      if (res.ret === 0) {
        that.axios
          .get("/api/verify", {
            params: {
              ticket: res.ticket,
              randstr: res.randstr
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              that.validate = true;
            }else {
              that.Fail("验证失败")
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    };
  },
  methods: {
    // getAppId() {
    //   this.axios.get('/api/getAppId').then(res => {
    //     if(res.data.code == 200) {
    //       this.appid = res.data.data.appid;
    //       console.log(this.appid)
    //     }
    //   }).catch(err => {
    //     console.log(err);
    //   })
    // },
    getCode() {
      this.axios
        .get("http://localhost:8081/sendEmail", {
          params: {
            to: this.form.email
          }
        })
        .then(res => {
          console.log(res);
          if (res.data.code != 200) {
            this.Fail("出错了T-T");
            this.clock = null;
            this.text = "发送验证码";
            this.times = 50;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    timer() {
      if (!this.clock) {
        this.clock = setInterval(() => {
          if (this.times > 0) {
            this.text = this.times + " s";
            this.times--;
          } else {
            clearInterval(this.clock);
            this.clock = null;
            this.text = "发送验证码";
            this.times = 59;
          }
        }, 1000);
      } else {
        this.warn();
      }
    },
    warn() {
      this.$message({
        showClose: true,
        message: "请不要重复点击哦~",
        type: "warning"
      });
    },
    login() {
      if (this.activeName == "email") {
        this.axios
          .get("http://localhost:8081/verifyEmailCode", {
            params: {
              code: this.form.code
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              alert("登录成功");
            } else {
              alert(res.data.msg);
            }
          });
        return;
      } else {
        if (
          this.form.username == "" ||
          this.form.password == "" ||
          this.validate == false
        ) {
          return;
        }
        let username = this.form.username;
        let password = this.form.password;
        console.log(username, password);
        this.axios
          .post("/api/login", {
            username: username,
            password: password
          })
          .then(res => {
            console.log(res.data);
            if (res.data.code === 200) {
              sessionStorage.setItem("token", res.data.data.token);
              this.getLoginStatus();
            } else {
              this.validate = false;
              this.Fail("登陆失败");
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    getLoginStatus() {
      this.axios
        .post("/api/user/findByName", {
          username: this.form.username
        })
        .then(res => {
          if (res.data.code == 200) {
            // console.log(res.data);
            sessionStorage.setItem("userId", res.data.data.id);
            this.$parent.userId = res.data.data.id;
            this.getRole();
            // console.log(sessionStorage.getItem("userId"));
            this.Success("登陆成功,将在三秒后跳转");
            setTimeout(() => {
              this.$router.push("/");
            }, 3000);
          } else {
            this.Fail("登录失败");
          }
        })
        .catch(error => {
          this.Fail("请求出错");
          console.log(error);
        });
    },
    Fail(index) {
      this.$message.error(index);
    },
    Success(index) {
      this.$message.success(index);
    },
    jumpTo() {
      this.$router.push("/register");
    },
    getRole() {
      this.userId = sessionStorage.getItem("userId");
      this.token = sessionStorage.getItem("token");
      this.axios
        .post("/api/getMenu", {
          Authorization: this.token
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            sessionStorage.setItem("isAdmin", true);
            this.$parent.isAdmin = true;
          }
        })
        .catch(error => {
          console.log(error);
          this.$parent.isAdmin = false;
        });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.login {
  position: relative;
  height: 100%;
  width: 100%;
  z-index: 20;
  background-color: white;
  /* position: relative; */
}
/* .content {
  height: 100%;
  overflow-x: hidden;
}
.content::-webkit-scrollbar {
  display: none;
} */
.el-container {
  height: 100%;

  overflow: hidden;
}
/* .el-container::-webkit-scrollbar {
  display: none;
} */
.el-header {
  margin-top: 20px;
}
.el-footer {
  text-align: right;
  line-height: 60px;
  background-color: transparent;
}
.el-aside {
  /* background-color: #d3dce6; */
  background-color: #6e7682;
  /* background-color: #0d1a2e; */
  color: #333;
  text-align: center;
  /* line-height: 200px; */
  line-height: 30px;
}

.el-main {
  width: 100%;
  height: 100%;
  /* background-color: #e9eef3; */
  color: #333;
  /* float: right; */
  /* text-align: center; */
  /* line-height: 160px; */
  overflow: hidden;
}
/* .el-main::-webkit-scrollbar{
  display: none;
} */

/* body > .el-container {
  margin-bottom: 40px;
} */
h1,
h2 {
  margin: 0;
  padding: 0;
}
h1 {
  color: #0d1a2e;
  font-size: 36px;
}
h2 {
  height: 60px;
}
.bg {
  /* background: url(../assets/login-bg2.png); */
  background: url(../assets/login.jpg);
  background-size: 100% 100%;
}
.box {
  width: 32%;
  /* margin-right: 10%; */
  margin-left: auto;
  margin-right: auto;

  /* margin-top: 30px; */
}
.box-card {
  /* height: 440px; */
  height: 100%;

  box-shadow: 8px 8px rgb(0, 0, 0, 0.3);
  border-radius: 30px;
  background-color: rgb(255, 255, 255, 0.3);
  /* height: 20%; */
  /* width: 300px;
    height: 300px; */
  /* margin: 60px auto; */
  /* padding: 30px; */
  /* padding: 30px; */
  /* background-color: rgba(255,255,255,0.2); */
}
.el-button {
  width: 100%;
}
.validate {
  width: 100%;
  /* height: 30px; */
  /* border-radius: 10%; */
  background-color: #fafafa;
}
.err {
  background-color: #f56c6c;
}
a {
  color: blue;
  text-decoration: none;
}
.el-tab-pane {
  height: 30px;
  /* padding: 20px 0; */
}
.title {
  color: #0d1a2e;
}
.form-data {
  width: 100%;
}
</style>
